package corsi.hibernate.demo.web.transazioni.services.impl;

import java.io.Serializable;
import java.util.List;
import java.util.logging.Logger;

import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.naming.InitialContext;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.hibernate.Session;

import corsi.hibernate.demo.web.transazioni.domain.AbstractValueObject;
import corsi.hibernate.demo.web.transazioni.domain.CD;
import corsi.hibernate.demo.web.transazioni.services.DemoTransazioniEEService;
import corsi.hibernate.demo.web.transazioni.services.exceptions.ServiceException;
import corsi.hibernate.demo.web.transazioni.services.util.HibernateUtil;

@TransactionManagement(value=TransactionManagementType.CONTAINER)
public class DemoTransazioniEEServiceImpl implements DemoTransazioniEEService {

	static Logger logger =Logger.getLogger("ServletDemoTransazioniJTA");
	   
	
	
	
	@Override
	public void aggiornaCatalogo(List<AbstractValueObject> prodotti)throws ServiceException {
		// TODO Auto-generated method stub
		
		// ThreadLocal Session
		/*
		Session sessione = HibernateUtil.getHibernateSession();
		
		try {

			sessione.getTransaction().begin();

			for (AbstractValueObject value : prodotti) {
				sessione.persist(value);
			}
			sessione.getTransaction().commit();

		} catch (Exception e) {
			sessione.getTransaction().rollback();
		}*/
		
		
		//JTA Session
		Session sessione; 
		UserTransaction tx=null;
		try{
			
			tx= (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
			tx.begin();
			sessione= HibernateUtil.getHibernateSession();
			for (AbstractValueObject value : prodotti) {
				sessione.persist(value);
				
			}
			tx.commit();
		
		} catch (Exception e) {
			try{
				tx.rollback();
			}catch (Exception ecc){
				
			}
			
		}
	}
 
	@Override
	@TransactionAttribute()
    public CD findCDByID(Long id) throws ServiceException {
		// TODO Auto-generated method stub
		Session sessione;
		UserTransaction tx=null;
		CD trovato =null;
		try{
		
			//url jndi per implementazione UserTransaction di JBoss
			tx= (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
			tx.begin();
			sessione= HibernateUtil.getHibernateSession();
			//sessione.getTransaction().begin();
			 trovato= (CD) sessione.get(CD.class, (Serializable)id);
			tx.commit();
			
			
		}catch (Exception e) {
			try{
				tx.rollback();
				throw new ServiceException(e.toString());
			}catch (SystemException ecc){
				
			}
			
			
		}
		return trovato;
	}

}
